<template>
  <div class="avatar-upload">
    <div class="avatar-container">
      <img v-if="avatarUrl" :src="avatarUrl" alt="User Avatar" class="avatar-preview" />
      <div v-else class="avatar-placeholder">
        <span>无头像</span>
      </div>
    </div>

    <div class="upload-controls">
      <input
        type="file"
        ref="fileInput"
        @change="handleFileSelect"
        accept="image/*"
        class="file-input"
      />
      <button @click="triggerFileInput" class="upload-button">选择图片</button>
      <button v-if="selectedFile" @click="uploadAvatar" class="confirm-button">上传头像</button>
      <button @click="getAvatar" class="confirm-button">获取已上传头像</button>
    </div>

    <p v-if="uploadError" class="error-message">{{ uploadError }}</p>
    <p v-if="uploadSuccess" class="success-message">{{ uploadSuccess }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const fileInput = ref(null);
const selectedFile = ref(null);
const avatarUrl = ref('');
const uploadError = ref('');
const uploadSuccess = ref('');

const triggerFileInput = () => {
  fileInput.value.click();
};

const handleFileSelect = (event) => {
  const file = event.target.files[0];
  if (file) {
    if (!file.type.startsWith('image/')) {
      uploadError.value = '请选中一张图片';
      return;
    }
    if (file.size > 2 * 1024 * 1024) {
      uploadError.value = '头像要求小于2M';
      return;
    }

    selectedFile.value = file;
    uploadError.value = '';

    const reader = new FileReader();
    reader.onload = (e) => {
      avatarUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const uploadAvatar = () => {
  if (!selectedFile.value) {
    uploadError.value = '请选择头像';
    return;
  }

  // Convert image to Base64
  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      // Extract base64 string (remove data:image/*;base64, prefix)
      const base64String = e.target.result.split(',')[1];
      axios
        .post('http://localhost:3000/user', {
          avatar: base64String,
          userId: 5,
          name: 'user1',
        })
        .then((response) => {
          uploadSuccess.value = '头像上传成功';
          console.log(response.data);
        })
        .catch((error) => {
          uploadError.value = error.message;
        });
    } catch (error) {
      uploadError.value = '转换失败: ' + (error.message || '未知错误');
    }
  };
  reader.readAsDataURL(selectedFile.value);
};

function getAvatar() {
  axios
    .get('http://localhost:3000/user/6825')
    .then((response) => {
      if (response.data.avatar) {
        const imageType = 'image/png';
        avatarUrl.value = `data:${imageType};base64,${response.data.avatar}`;
      } else {
        avatarUrl.value = '';
      }
    })
    .catch((error) => {
      uploadError.value = error.message;
    });
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  max-width: 400px;
  margin: 0 auto;
}

.avatar-container {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px dashed #ccc;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: #999;
  font-size: 14px;
}

.upload-controls {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: center;
  margin-bottom: 10px;
}

.file-input {
  display: none;
}

.upload-button,
.confirm-button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.upload-button {
  background-color: #409eff;
  color: white;
}

.confirm-button {
  background-color: #67c23a;
  color: white;
}

.upload-button:hover {
  background-color: #66b1ff;
}

.confirm-button:hover {
  background-color: #85ce61;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  margin: 5px 0;
}

.success-message {
  color: #67c23a;
  font-size: 14px;
  margin: 5px 0;
}
</style>
